//
//  StyleData.swift
//  
//
//  Created by 孙长坦 on 2022/6/17.
//

import Foundation
import UIKit

public struct StyleData: Codable {
    enum CodingKeys: String, CodingKey {
        case color
        case fontData = "font"
        case fontSize
    }
    
    @ColorWrapper
    public var color: UIColor?
    
    public let fontData: FontData?
    
    public init(color: UIColor? = nil, fontData: FontData? = nil) {
        self.color = color
        self.fontData = fontData
    }
    
    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        color = try? container.decodeIfPresent(ColorWrapper.self, forKey: .color)?.wrappedValue
        
        fontData = (try? container.decode(FontData.self, forKey: .fontData)) ??
            (try? container.decodeIfPresent(FontData.self, forKey: .fontSize))
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try container.encodeIfPresent(ColorWrapper(wrappedValue: color), forKey: .color)
 
        try container.encodeIfPresent(fontData, forKey: .fontData)
    }
}
